import type { FC } from "react";
import { useState, useEffect } from "react";
import RobotIcon from "../assets/robot.svg";
import Avatar from "./ui/Avatar";
import userService from "../utils/userService";
import { userLoginOut } from "../services/login/loginout";
import alertService from "../utils/alertService";
import dialogService from "../utils/dialogService";

interface HeaderProps {
  onNewChat?: () => void;
  onToggleSidebar?: () => void;
  isSidebarOpen?: boolean;
  onLogin?: () => void;
}

const Header: FC<HeaderProps> = ({
  onToggleSidebar,
  isSidebarOpen = false,
  onLogin = () => {},
}) => {
  const [isDarkMode, setIsDarkMode] = useState(false);
  // 用户登录状态
  const [isLoggedIn, setIsLoggedIn] = useState(userService.isLoggedIn);
  // 用户头像
  const [avatarUrl, setAvatarUrl] = useState(
    userService.userInfo?.avatar || null
  );

  // 初始化主题和用户状态
  useEffect(() => {
    // 检查本地存储中的主题偏好
    const savedTheme = localStorage.getItem("theme");
    const prefersDark = window.matchMedia(
      "(prefers-color-scheme: dark)"
    ).matches;

    // 设置初始主题状态
    const initialDarkMode =
      savedTheme === "dark" || (!savedTheme && prefersDark);
    setIsDarkMode(initialDarkMode);

    // 应用主题到HTML元素
    if (initialDarkMode) {
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }

    // 立即检查一次当前登录状态
    const currentLoginStatus = userService.isLoggedIn;
    const currentAvatar = userService.userInfo?.avatar || null;

    setIsLoggedIn(currentLoginStatus);
    setAvatarUrl(currentAvatar);

    // 订阅用户状态变化
    const unsubscribe = userService.subscribe(() => {
      console.log("[Header] 用户状态变化通知:", userService.isLoggedIn);
      setIsLoggedIn(userService.isLoggedIn);
      setAvatarUrl(userService.userInfo?.avatar || null);
    });

    // 组件卸载时取消订阅
    return unsubscribe;
  }, []);

  // 添加定期检查登录状态
  useEffect(() => {
    const checkInterval = setInterval(() => {
      const currentLoginStatus = userService.isLoggedIn;
      if (currentLoginStatus !== isLoggedIn) {
        console.log("[Header] 登录状态变化:", currentLoginStatus);
        setIsLoggedIn(currentLoginStatus);
        setAvatarUrl(userService.userInfo?.avatar || null);
      }
    }, 1000); // 每秒检查一次

    return () => clearInterval(checkInterval);
  }, [isLoggedIn]);

  // 切换主题
  const toggleTheme = () => {
    setIsDarkMode((prev) => {
      const newDarkMode = !prev;

      // 更新本地存储中的主题偏好
      localStorage.setItem("theme", newDarkMode ? "dark" : "light");

      // 应用主题到HTML元素
      if (newDarkMode) {
        document.documentElement.classList.add("dark");
      } else {
        document.documentElement.classList.remove("dark");
      }

      return newDarkMode;
    });
  };

  // 处理登出
  const handleLogout = async () => {
    try {
      // 使用dialogService显示登出确认对话框
      const confirmed = await dialogService.confirmLogout();

      if (confirmed) {
        // 调用登出API
        const response = await userLoginOut();
        if (response.code === 200) {
          // API请求成功，执行本地登出操作
          userService.logout();
          // 可选：清除会话列表等其他数据
          // sessionStorage.clear(); // 如果需要清除会话存储
          alertService.success("已成功退出登录");
        }
      }
    } catch (error) {
      console.error("登出过程发生错误:", error);
      // 发生错误时仍然执行本地登出
      userService.logout();
      alertService.warning("登出请求发生错误，已清除本地登录状态");
    }
  };

  // 处理登录或登出按钮点击
  const handleAuthAction = () => {
    if (isLoggedIn) {
      // 如果已登录，执行登出
      handleLogout();
    } else {
      // 如果未登录，调用登录方法
      onLogin();
    }
  };

  return (
    <header className="bg-white dark:bg-gray-800 shadow-sm w-full">
      <div className="max-w-full px-2 md:px-4 py-3 flex items-center justify-between">
        <div className="flex items-center">
          <button
            onClick={onToggleSidebar}
            className="md:hidden text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 p-1.5 rounded-md mr-2"
            aria-label={isSidebarOpen ? "关闭菜单" : "打开菜单"}
          >
            {isSidebarOpen ? (
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-6 w-6"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            ) : (
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-6 w-6"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M4 6h16M4 12h16M4 18h16"
                />
              </svg>
            )}
          </button>
          <div className="flex items-center">
            {/* 使用导入的机器人图标 */}
            <div className="mr-2">
              <img
                src={RobotIcon}
                alt="Robot"
                className="h-6 w-6 md:h-7 md:w-7"
              />
            </div>
            <h1 className="text-lg md:text-xl font-bold text-[#1296db]">
              Cirno AI
            </h1>
          </div>
        </div>
        <div className="flex items-center space-x-2">
          {/* 头像，登录后才显示，移除onClick事件 */}
          {isLoggedIn && (
            <Avatar
              src={avatarUrl}
              size="md"
              alt={userService.userInfo?.nickname || "用户头像"}
            />
          )}

          {/* 登录/登出按钮 */}
          <button
            onClick={handleAuthAction}
            className="text-[#1296db] hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/20 px-3 py-1 rounded-full text-sm font-medium transition-colors border border-[#1296db]/30 dark:border-blue-500/30"
          >
            {isLoggedIn ? "Exit" : "Login"}
          </button>

          {/* 主题切换按钮 */}
          <button
            onClick={toggleTheme}
            className="text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 p-1.5 rounded-full transition-colors"
            aria-label={isDarkMode ? "切换到亮色模式" : "切换到暗色模式"}
          >
            {isDarkMode ? (
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-5 w-5"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"
                />
              </svg>
            ) : (
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-5 w-5"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"
                />
              </svg>
            )}
          </button>
        </div>
      </div>
    </header>
  );
};

export default Header;
